package com.example.demo.thread.juc;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

/**
 * @Description: CyclicBarrier 循环屏障
 * @Author: LLL
 * @Date: 2020-03-19 19:06
 **/
public class CyclicBarrierDemo {
    public static void main(String[] args) {
        CyclicBarrier barrier = new CyclicBarrier(7, () -> {
            System.out.println("召唤神龙、、、、、");
        });
        for (int i = 1; i <= 7; i++) {
            final int te = i;
            new Thread(() -> {
                System.out.println(Thread.currentThread().getName() + "收集到第" + te + "颗龙珠");
                try {
                    // 等到最后一个线程收集到最后一颗龙珠时，才能执行召唤神龙
                    barrier.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (BrokenBarrierException e) {
                    e.printStackTrace();
                }
            }, "" + te).start();
        }
    }
}
